package com.hula.onion.book.server.spider.platforms.xiaozhulicai;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:49
 *
 * @author shan
 * @version 1.0
 */
@Component
public class XiaoZhuLiCaiSpiderHelper {

    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form) {

        Map<String, Object> map = new HashMap<>(3);
        map.put("phone", form.getUserName());
        map.put("user_passwd", form.getPassword());
        map.put("verify", form.getTicket());
        return map;

    }

    public boolean checkLogin(String html) {
        try {
            Document document = Jsoup.parse(html);
            Element element = document.selectFirst("div.error-desc");
            String msg = element.children().get(1).text().trim();
            if ("登录验证成功！".equals(msg)) {
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 解析账户余额
     *
     * @param html
     * @return
     */
    public CommonResponse parseAccountBalance(String html) {

        try {
            AccountInfo accountInfo = new AccountInfo();

            Document dc = Jsoup.parse(html);
            String yesterdayInterest = dc.selectFirst("p.yestoday").
                    children().get(1).text();
            String totalInterest = dc.selectFirst("p.total").
                    children().get(1).text();
            String total = dc.selectFirst("div.pie").
                    children().get(1).children().get(0).text();
            accountInfo.setYesterdayIntrest(new BigDecimal(yesterdayInterest));
            accountInfo.setTotalIntrest(new BigDecimal(totalInterest));
            accountInfo.setAmount(new BigDecimal(total));
            return new CommonResponse(accountInfo);

        } catch (Exception e) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }

    }


}
